package app.dao.test;

import vn.bang.xiangqi.server.AbstractBaseServer;
import vn.bang.xiangqi.server.IServer;

import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Button.ClickEvent;

public class ServerControllerPanel extends Panel {
	private static final long serialVersionUID = 1L;
	
	private static final String STOPPED_STATUS = "Server STOPPED";
	private static final String STARTED_STATUS = "Server STARTED";
	
	private VerticalLayout verticalLayout = new VerticalLayout();
	private Button btnStartServer = new Button("Start");
	private Button btnStopServer = new Button("Stop");
	private Label lblStatus = new Label(STOPPED_STATUS);
	
	private IServer server;
	
	public ServerControllerPanel(String caption) {
		setCaption(caption);
		
		btnStartServer.addListener(new ClickListener() {
			private static final long serialVersionUID = 1L;

			public void buttonClick(ClickEvent event) {
				start();
				startupServer(server);
			}
		});
		
		btnStopServer.addListener(new ClickListener() {
			private static final long serialVersionUID = 1L;

			public void buttonClick(ClickEvent event) {
				stop();
				shutdownServer(server);
			}
		});
		
		verticalLayout.addComponent(btnStartServer);
		verticalLayout.addComponent(btnStopServer);
		verticalLayout.addComponent(lblStatus);
		setContent(verticalLayout);
	}
	
	public void start() {
		lblStatus.setValue(STARTED_STATUS);
		btnStartServer.setEnabled(Boolean.FALSE);
		btnStopServer.setEnabled(Boolean.TRUE);
	}
	
	public void stop() {
		lblStatus.setValue(STOPPED_STATUS);
		btnStartServer.setEnabled(Boolean.TRUE);
		btnStopServer.setEnabled(Boolean.FALSE);
	}
	
	public void setServer(IServer server) {
		this.server = server;
		if (AbstractBaseServer.START_STATUS.equals(server.getStatus())) {
			start();
		} else if (AbstractBaseServer.STOP_STATUS.equals(server.getStatus())) {
			stop();
		}
	}
	
	public IServer getServer() {
		return server;
	}
	
	private void startupServer(IServer server) {
		if (null != server) {
			server.startup();
		}
	}
	
	private void shutdownServer(IServer server) {
		if (null != server) {
			server.shutdown();
		}
	}
}
